package com.tiyende.kash.loop.ui.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.graphics.toColorInt
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.common.CommonFragment
import com.tiyende.kash.loop.databinding.TiyendeFragmentWithdrawBinding
import com.tiyende.kash.loop.event.TiyendeEventData
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.ui.activity.TiyendeAuthenticationStepsActivity
import com.tiyende.kash.loop.ui.activity.TiyendeLimitRejectedActivity
import com.tiyende.kash.loop.ui.activity.TiyendeLimitReviewingActivity
import com.tiyende.kash.loop.ui.activity.TiyendeLoanApplyActivity
import com.tiyende.kash.loop.ui.activity.TiyendeLoanCalculatorActivity
import com.tiyende.kash.loop.ui.activity.TiyendeOrderListActivity
import com.tiyende.kash.loop.ui.activity.TiyendePermissionListActivity
import com.tiyende.kash.loop.ui.contract.IViewContract
import com.tiyende.kash.loop.ui.dialog.TiyendePermissionReasonDialog
import com.tiyende.kash.loop.ui.dialog.TiyendeTipsDialog
import com.tiyende.kash.loop.ui.presenter.TiyendeWithdrawPresenter
import com.tiyende.kash.loop.utils.helper.TiyendeOrderHelper
import com.tiyende.kash.loop.utils.helper.TiyendePermissionHelper
import com.tiyende.kash.loop.utils.helper.TiyendeProcessHelper
import com.tiyende.kash.loop.utils.helper.TiyendeStatusHelper
import com.tiyende.kash.loop.utils.log.TiyendeLogger
import com.tiyende.kash.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.kash.loop.utils.shared.TiyendeSharedKey
import com.tiyende.kash.loop.utils.track.TrackPointManager
import org.json.JSONObject
import java.math.BigDecimal
import java.math.RoundingMode

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：主页
 */
class TiyendeWithdrawFragment: CommonFragment(), IViewContract.ITiyendeWithdrawView {
    // 使用可空类型的 backing property
    private var _binding: TiyendeFragmentWithdrawBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    var presenter: TiyendeWithdrawPresenter? = null
    private var showLimitType = 0
    override fun getTiyendeRootView(inflater: LayoutInflater): View {
        _binding = TiyendeFragmentWithdrawBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        _binding?.creditLimitRefreshLayout?.setColorSchemeResources(R.color.theme,R.color.purple_500)
        _binding?.creditLimitLayout?.visibility = View.INVISIBLE
    }

    override fun initTiyendeListener() {
        _binding?.creditLimitRefreshLayout?.setOnRefreshListener {
            publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESH))
            publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_ORDER_REFRESH))
        }
        _binding?.txtAvaliableLimit?.setOnClickListener {
            showLimitType = 0
            showWithdrawCheckLimitViews()
        }
        _binding?.txtUtilisedLimit?.setOnClickListener {
            showLimitType = 1
            showWithdrawCheckLimitViews()
        }
        _binding?.txtTotalLimit?.setOnClickListener {
            showLimitType = 2
            showWithdrawCheckLimitViews()
        }
        _binding?.btWithdraw?.setOnClickListener {
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_HOME_WITHDRAW_NOW)
            // TODO: 首页点 Withdraw Now 上报所有埋点
            TrackPointManager.getInstance().manualReport()
            presenter?.checkTiyendeWithdrawPermissionsAgree()
        }

        //订单列表
        _binding?.queryOrderLayout?.setOnClickListener {
            onIntent(TiyendeOrderListActivity::class.java)
        }
        //计算器
        _binding?.imageLoanCalculator?.setOnClickListener {
            onIntent(TiyendeLoanCalculatorActivity::class.java)
        }
    }

    override fun loadTiyendeData() {
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_WITHDRAW_START)
        if (presenter == null){
            presenter = TiyendeWithdrawPresenter(this)
        }
    }

    /**
     * 权限声明列表
     */
    private val permissionResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                var isNext = false
                result.data?.let { bundle ->
                    val isAgree = bundle.getBooleanExtra("isPermissionAgree",false)
                    TiyendeLogger.e(">>>>>>>>>permission is agree ：$isAgree")
                    //同意，校验权限 进行下一步
                    isNext = if (isAgree){
                        true
                    } else {//拒绝，
                        //是否是广告渠道
                        val isAdSource = TiyendeSharedHelper.queryTiyendeSharedBoolean(TiyendeSharedKey.TIYENDE_IS_ADSOURCE)
                        //非广告渠道才继续校验进行下一步
                        !isAdSource
                    }
                }
                if (isNext){
                    presenter?.checkTiyendeWithdrawPermissionsAgree()
                }
            }
        }
    }

    /**
     * 显示额度信息
     */
    @SuppressLint("SetTextI18n")
    override fun showTiyendeLimitInfo(data: JSONObject) {
        _binding?.creditLimitLayout?.visibility = View.VISIBLE
        //订单数量
        _binding?.txtOrderCount?.text = String.format(getString(R.string.tiyende_withdraw_count),TiyendeOrderHelper.queryTiyendeOrderOtherList().size.toString())
        //已使用额度
        _binding?.txtUtilisedAmount?.text = "${BigDecimal(data.optString("utilisedAmount")).stripTrailingZeros().toPlainString()} ${data.optString("currency")}"
        //开始发送通知检查是否有更新
        publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_SHOW_HOME_UPDATE))

        // 进件信息未完成
        if (TiyendeProcessHelper.queryTiyendeAuthenticationStepList().isNotEmpty()){
            showTiyendeLimitCreditBeforViews(data)
            return
        }

        val isCreditReviewing = TiyendeStatusHelper.TiyendeCreditStatusRepository().isCreditReviewing()
        //授信中(未处理)
        if (isCreditReviewing){
            showTiyendeLimitCreditingViews()
            return
        }

        val creditStatus = TiyendeProcessHelper.queryTiyendeAuthenticationBeforeRiskStatus()
        val isCreditRejected = TiyendeStatusHelper.TiyendeCreditStatusRepository().isCreditRejected(creditStatus)
        //已拒绝
        if (isCreditRejected){
            showTiyendeLimitCreditBeforViews(data)
            return
        }

        // 授信通过 && 进件信息已完成 - 获取额度
        showTiyendeLimitCreditedViews(data)
    }

    /**
     * 未授信页面
     */
    @SuppressLint("SetTextI18n")
    override fun showTiyendeLimitCreditBeforViews(data: JSONObject) {
        _binding?.txtExpirse?.text = " : **/**/****"
        _binding?.txtLimitPercentage?.visibility = View.VISIBLE
        _binding?.txtLimitPercentage?.text = getString(R.string.tiyende_withdraw_not_activated)
        _binding?.txtExpirseTips?.visibility = View.GONE
        _binding?.txtAmount?.text = "***.***"
        _binding?.imageLimitStatus?.setImageResource(R.mipmap.tiyende_withdraw_progress_default)
        _binding?.btWithdraw?.text = getString(R.string.tiyende_withdraw_activate_now)
        _binding?.btWithdraw?.isEnabled = true
    }

    /**
     * 授信中
     */
    private fun showTiyendeLimitCreditingViews(){
        _binding?.txtExpirse?.text = " : **/**/****"
        _binding?.txtLimitPercentage?.visibility = View.VISIBLE
        _binding?.txtLimitPercentage?.text = getString(R.string.tiyende_withdraw_credit_limit_is_calculating2)
        _binding?.txtExpirseTips?.visibility = View.VISIBLE
        _binding?.txtExpirseTips?.text = getString(R.string.tiyende_withdraw_credit_limit_is_calculating)
        _binding?.txtAmount?.text = "***.***"
        _binding?.imageLimitStatus?.setImageResource(R.mipmap.tiyende_withdraw_progress_default)
        _binding?.btWithdraw?.text = getString(R.string.tiyende_withdraw_credit_limit_is_calculating)
        _binding?.btWithdraw?.isEnabled = false
    }

    /**
     * 授信已完成
     */
    @SuppressLint("SetTextI18n")
    override fun showTiyendeLimitCreditedViews(data: JSONObject) {
        _binding?.txtExpirse?.text = " : ${TiyendeProcessHelper.queryTiyendeAuthenticationCreditExpireDate()}"
        _binding?.txtExpirseTips?.visibility = View.VISIBLE
        _binding?.txtExpirseTips?.text = getString(R.string.tiyende_withdraw_expires_tips)

        //可用额度
        val availableAmount = BigDecimal(data.optString("availableAmount")).stripTrailingZeros().toPlainString()
        //已使用额度
        val utilisedAmount = BigDecimal(data.optString("utilisedAmount")).stripTrailingZeros().toPlainString()
        //总额度
        val totalAmount = BigDecimal(availableAmount).add(BigDecimal(utilisedAmount)).stripTrailingZeros().toPlainString()
        //额度百分比
        when(showLimitType){
            0 -> {//可用额度
                _binding?.txtLimitPercentage?.visibility = View.VISIBLE
                //剩余可用百分比
                val showText = BigDecimal(availableAmount).divide(BigDecimal(totalAmount.toString()),2, RoundingMode.UP).multiply(BigDecimal("100")).stripTrailingZeros().toPlainString()
                _binding?.txtLimitPercentage?.text = String.format(getString(R.string.tiyende_withdraw_remaining_amount),"$showText%")
                _binding?.txtAmount?.setTextColor("#FF3ED9AB".toColorInt())
                _binding?.txtAmount?.text = availableAmount
            }
            1 -> {//已使用额度
                _binding?.txtLimitPercentage?.visibility = View.VISIBLE
                //已使用百分比
                val showText = BigDecimal(utilisedAmount).divide(BigDecimal(totalAmount.toString()),2, RoundingMode.UP).multiply(BigDecimal("100")).stripTrailingZeros().toPlainString()
                _binding?.txtLimitPercentage?.text = String.format(getString(R.string.tiyende_withdraw_utilised_amount),"$showText%")
                _binding?.txtAmount?.setTextColor("#FF084843".toColorInt())
                _binding?.txtAmount?.text = utilisedAmount
            }
            2 -> {//总额度
                _binding?.txtLimitPercentage?.visibility = View.INVISIBLE
                _binding?.txtAmount?.setTextColor("#FF3ED9AB".toColorInt())
                _binding?.txtAmount?.text = totalAmount
            }
        }
        _binding?.btWithdraw?.isEnabled = availableAmount.toLong() > 0
        if (utilisedAmount.toLong() <= 0){//未使用
            _binding?.btWithdraw?.text = getString(R.string.tiyende_withdraw_now)
            _binding?.imageLimitStatus?.setImageResource(R.mipmap.tiyende_withdraw_progress_default)
            return
        }
        _binding?.btWithdraw?.text = getString(R.string.tiyende_withdraw_more)
        if (availableAmount.toLong() <= 0){//额度已用完
            _binding?.imageLimitStatus?.setImageResource(R.mipmap.tiyende_withdraw_progress_exhausted)
            return
        }
        //已使用 && 额度未用完
        if (availableAmount.toLong() < utilisedAmount.toLong()){//可用额度 > 已使用额度
            _binding?.imageLimitStatus?.setImageResource(R.mipmap.tiyende_withdraw_progress_top)
        } else {
            _binding?.imageLimitStatus?.setImageResource(R.mipmap.tiyende_withdraw_progress_bottom)
        }
    }

    /**
     * 权限
     */
    override fun showTiyendeWithdrawPermissionPage() {
        permissionResultLauncher.launch(Intent(context, TiyendePermissionListActivity::class.java))
    }

    /**
     * 申贷
     */
    override fun showTiyendeWithdrawApplyPage() {
        TiyendeLoanApplyActivity.start(requireContext())
    }

    /**
     * 填写进件信息
     */
    override fun showTiyendeWithdrawAUthenticationStepsPage() {
        onIntent(TiyendeAuthenticationStepsActivity::class.java)
    }

    /**
     * 授信拒绝
     */
    override fun showTiyendeWithdrawCreditRejectedPage() {
        onIntent(TiyendeLimitRejectedActivity::class.java)
    }

    /**
     * 授信额度审核中
     */
    override fun showTiyendeWithdrawCreditReviewPage() {
        onIntent(TiyendeLimitReviewingActivity::class.java)
    }

    /**
     * 切换显示内容
     */
    private fun showWithdrawCheckLimitViews(){
        _binding?.txtAvaliableLimit?.setTextColor("#FF000000".toColorInt())
        _binding?.txtUtilisedLimit?.setTextColor("#FF000000".toColorInt())
        _binding?.txtTotalLimit?.setTextColor("#FF000000".toColorInt())
        _binding?.imageAvaliableLimit?.visibility = View.INVISIBLE
        _binding?.imageUtilisedLimit?.visibility = View.INVISIBLE
        _binding?.imageTotalLimit?.visibility = View.INVISIBLE
        when(showLimitType){
            0 -> {//可用额度
                _binding?.txtAvaliableLimit?.setTextColor("#FFFFFFFF".toColorInt())
                _binding?.imageAvaliableLimit?.visibility = View.VISIBLE
            }
            1 -> {//已使用额度
                _binding?.txtUtilisedLimit?.setTextColor("#FFFFFFFF".toColorInt())
                _binding?.imageUtilisedLimit?.visibility = View.VISIBLE
            }
            else -> {//总额度
                _binding?.txtTotalLimit?.setTextColor("#FFFFFFFF".toColorInt())
                _binding?.imageTotalLimit?.visibility = View.VISIBLE
            }
        }

        val limitData = presenter?.amountInfo
        limitData?.let {
            showTiyendeLimitInfo(it)
        }
    }

    /**
     * 存在被拒绝的订单提示
     */
    override fun showTiyendeWithdrawOrderRejectedDialog() {
        val againApplyDate = TiyendeProcessHelper.queryTiyendeAuthenticationApplyAgainDate()
        val showText = String.format(getString(R.string.tiyende_dialog_apply_error_tips),againApplyDate)
        val spString = SpannableString(showText)
        val start = showText.indexOf(againApplyDate)
        spString.setSpan(ForegroundColorSpan("#FF3ED9AB".toColorInt()), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        val errorDialog = TiyendeTipsDialog(requireContext(),"Order Rejected")
        errorDialog.setCancelable(true)
        errorDialog.setCanceledOnTouchOutside(true)
        errorDialog.show()
        errorDialog.addTiyendeTipsIconResource(R.mipmap.tiyende_dialog_tips_icon)
        errorDialog.addTiyendeBtnOkText(getString(R.string.tiyende_button_ok))
        errorDialog.addTiyendeBtnCancelText(getString(R.string.tiyende_button_cancel))
        errorDialog.addTiyendeTipsText(spString)
    }

    /**
     * 模拟权限声明dialog
     */
    fun showTiyendePermissionReasonDialog(){
        val item = TiyendePermissionHelper.queryTiyendeCameraItem()
        val reasonDialog = TiyendePermissionReasonDialog(requireContext(),"Selfie Page",object: TiyendePermissionReasonDialog.IDialogCallback{
            override fun onTiyendePermissionDenyClick() {
                showTiyendeToast("click deny")
            }
            override fun onTiyendePermissionAgreeClick() {
                showTiyendeToast("click agree")
            }
        })
        reasonDialog.setCancelable(true)
        reasonDialog.setCanceledOnTouchOutside(true)
        reasonDialog.show()
        reasonDialog.showTiyendePermissionReasonItem(item)
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESHED -> { //刷新流程完成
                _binding?.let {
                    if (!it.creditLimitRefreshLayout.isRefreshing){
                        showTiyendeLoading()
                    }
                }
                presenter?.queryTiyendeLimitCreditAction()
            }
            TiyendeEventData.TYPE.TIYENDE_WITHDRAW_LIMIT_REFRESH -> {//刷新首页额度信息
                presenter?.queryTiyendeLimitCreditAction()
            }
            TiyendeEventData.TYPE.TIYENDE_ORDER_REFRESHED -> {//订单刷新完成
                _binding?.txtOrderCount?.text = String.format(getString(R.string.tiyende_withdraw_count),TiyendeOrderHelper.queryTiyendeOrderOtherList().size.toString())
            }
            TiyendeEventData.TYPE.TIYENDE_SHOW_AUTHENTICATION -> {
                _binding?.btWithdraw?.callOnClick()
            }
            TiyendeEventData.TYPE.TIYENDE_REQUEST_ERROR -> {
                hiddenTiyendeLoading()
            }
            else -> {

            }
        }
    }

    override fun hiddenTiyendeLoading() {
        super.hiddenTiyendeLoading()
        _binding?.creditLimitRefreshLayout?.isRefreshing = false
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_WITHDRAW_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}